<template>
  <!-- <Teleport to="body"></Teleport> 将元素放到指定层级上 -->
  <transition name="fade">
    <div class="my-drawer" ref="drawerRef" v-if="visible" :style="drawerStyle">
      <div class="change-size-icon" @mousedown="handleMouseDown" @mousemove="handleMouseMove" @mouseup="handleMouseUp">
        <el-tooltip content="按住鼠标左键上下移动可修改弹框大小" placement="top-start" effect="customized">
          <SvgIcon name="svg-move"></SvgIcon>
        </el-tooltip>
      </div>
      <slot name="content"></slot>
    </div>
  </transition>
</template>
<script setup lang="ts">
const $emit = defineEmits(['update:visible']);
const globalStore = useGlobalStore();
const props = defineProps({
  // 是否显示
  visible: {
    type: Boolean,
    default: false
  },
  // 是否可关闭弹框
  isClose: {
    type: Boolean,
    default: true
  }
});

const drawerRef = ref();

// 是否可移动
let isMove = ref(false);
let createLocation = ref(0);

const drawerStyle = computed(() => {
  return {
    height: `calc(50% - ${globalStore.drawerHeight}px)`
  };
});

onMounted(() => {
  document.addEventListener('mouseup', handleMouseUp);
});

/**
 * @description: 鼠标按下
 * @return {*}
 */
const handleMouseDown = (event: MouseEvent) => {
  createLocation.value = event.clientY - globalStore.drawerHeight;
  document.addEventListener('mousemove', handleMouseMove);
  isMove.value = true;
};

/**
 * @description: 鼠标移动
 * @return {*}
 */
const handleMouseMove = (event: MouseEvent) => {
  if (isMove.value) {
    const height = event.clientY - createLocation.value < 220 ? event.clientY - createLocation.value : 220;
    globalStore.setGlobalState('drawerHeight', height);
  } else {
    document.removeEventListener('mousemove', handleMouseMove);
  }
};

/**
 * @description: 鼠标松开
 * @return {*}
 */
const handleMouseUp = () => {
  isMove.value = false;
  document.removeEventListener('mousemove', handleMouseMove);
};

const handleClickOutside = (event: MouseEvent) => {
  if (props.visible && props.isClose && drawerRef.value && !drawerRef.value?.contains(event.target as Node)) {
    $emit('update:visible', false);
  }
};

onMounted(() => {
  document.addEventListener('click', handleClickOutside);
});
</script>
<style lang="scss" src="./index.scss" scoped></style>
